using GameFramework.Event;
using GameFramework.Localization;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityGameFramework.Runtime;
using VRLauncher;

public class UpdateForm : UGuiForm
{
    [SerializeField]
    private Button OnUpdateBtn;
    [SerializeField]
    private Button OnBackBtn;
    [SerializeField]
    private Button OnChineseSBtn;
    [SerializeField]
    private Button OnChineseTBtn;
    [SerializeField]
    private Button OnEnglishBtn;
    [SerializeField]
    private Button OnKoreanBtn;

    private Language m_SelectedLanguage = Language.Unspecified;
    protected override void OnInit(object userData)
    {

        base.OnInit(userData);
        OnUpdateBtn.onClick.AddListener(() =>
        {
            PlayerPrefs.SetInt(PlayerPrefsKey.ManualUpdate, 1);
            RestartApplication();
        });

        OnBackBtn.onClick.AddListener(() =>
        {

            GameManager.UI.CloseUIForm(this);
        });
        OnChineseSBtn.onClick.AddListener(()=> { OnSetLanguageButtonClick(Language.ChineseSimplified); });
        OnChineseTBtn.onClick.AddListener(() => { OnSetLanguageButtonClick(Language.ChineseTraditional); });
        OnEnglishBtn.onClick.AddListener(() => { OnSetLanguageButtonClick(Language.English); });
        OnKoreanBtn.onClick.AddListener(() => { OnSetLanguageButtonClick(Language.Korean); });
    }


    protected override void OnReveal()
    {
        ChecheckUpdate();
    }
    protected override void OnCover()
    {
        //注销text组件查询字典重赋值事件
       // UnregisterLacalizationEven();
    }

    void ChecheckUpdate()
    {
        StartCoroutine(UpdateOpinion());
    }
    //读取更新版本
    IEnumerator UpdateOpinion()
    {

        //读取服务器版本号比对后显示更新按钮
        string url = GetVersionURL();


        Log.Info(url);
        UnityWebRequest request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();
        if (request.result != UnityWebRequest.Result.ProtocolError || request.result != UnityWebRequest.Result.ConnectionError)
        {
            string UpdateVersion = request.downloadHandler.text;
            Log.Info("更新版本:" + UpdateVersion);
            Log.Info("本地版本:" + PlayerPrefs.GetString(PlayerPrefsKey.LocalVersion));

            if (UpdateVersion != PlayerPrefs.GetString(PlayerPrefsKey.LocalVersion))
            {
                OnUpdateBtn.GetComponent<CanvasGroup>().alpha = 1;
            }
            else
            {
                Log.Info("The remote version is the same as the local version");
            }
        }
        else
        {
            Log.Warning("Internet Connect Error");
        }
    }

    /// <summary>
    /// 获取资源服务器地址
    /// </summary>
    private static string GetVersionURL()
    {
        string hostServerIP = MessagingHelper.hostIpAddress;
        string appVersion = "DefaultPackage/PackageManifest_DefaultPackage.version";

#if UNITY_EDITOR
        if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.Android)
            return $"{hostServerIP}/CDN/Android/{appVersion}";
        else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.iOS)
            return $"{hostServerIP}/CDN/IPhone/{appVersion}";
        else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.WebGL)
            return $"{hostServerIP}/CDN/WebGL/{appVersion}";
        else
            return $"{hostServerIP}/CDN/PC/{appVersion}";
#else
        if (Application.platform == RuntimePlatform.Android)
            return $"{hostServerIP}/CDN/Android/{appVersion}";
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
            return $"{hostServerIP}/CDN/IPhone/{appVersion}";
        else if (Application.platform == RuntimePlatform.WebGLPlayer)
            return $"{hostServerIP}/CDN/WebGL/{appVersion}";
        else
            return $"{hostServerIP}/CDN/PC/{appVersion}";
#endif
    }

    // 根据不同平台重启应用
    private void RestartApplication()
    {
        // 判断平台类型
        if (Application.isEditor)
        {
            Log.Info("在编辑器中，不能重启");
        }
        else if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor)
        {
            ReStart_Win();
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            Log.Info("在 Android 平台，重新启动应用");
            // 在 Android 上可以使用 Unity 提供的重启方法
            AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject obj = jc.GetStatic<AndroidJavaObject>("currentActivity");
            obj.Call("recreate");
        }
        else
        {
            Log.Warning($"不支持的运行平台: {Application.platform}，无法重启应用");
        }
    }


    public void ReStart_Win()
    {
        // 延迟 1 秒启动
        string[] strs = new string[]
        {
            "@echo off",
            "echo wscript.sleep 100 > sleep.vbs", // 创建一个延迟 0.1 秒的 vbs 脚本
            "start /wait sleep.vbs",                // 执行 vbs 脚本，等待 0.1 秒
            "start /d \"{0}\" {1}",                 // 启动应用程序（应用路径和应用名称）
            "del /f /s /q sleep.vbs",               // 删除 vbs 脚本
            "exit"
        };

        // 获取应用程序所在目录的路径
        string path = Application.dataPath + "/../";

        // 获取所有可执行文件（.exe）路径
        List<string> prefabs = new List<string>(Directory.GetFiles(path, "*.exe", SearchOption.AllDirectories));

        // 遍历所有可执行文件，查找目标应用程序并生成批处理文件
        foreach (string keyx in prefabs)
        {
            string _path = Application.dataPath;
            _path = _path.Remove(_path.LastIndexOf("/")) + "/"; // 获取应用程序目录路径
            Log.Error(_path); // 输出路径信息（可选）

            string _name = Path.GetFileName(keyx); // 获取可执行文件名

            // 排除 UnityCrashHandler64.exe
            if (_name.Equals("UnityCrashHandler64.exe"))
            {
                continue; 
            }

            // 将路径和文件名替换到批处理脚本中
            strs[3] = string.Format(strs[3], _path, _name); // 生成启动命令

            // 创建批处理文件路径
            string batPath = path + "restart.bat";
            if (File.Exists(batPath))
            {
                File.Delete(batPath); // 如果文件已存在，删除旧的批处理文件
            }

            // 创建并写入批处理文件
            using (FileStream fileStream = File.OpenWrite(batPath))
            {
                using (StreamWriter writer = new StreamWriter(fileStream, System.Text.Encoding.UTF8))
                {
                    foreach (string s in strs)
                    {
                        writer.WriteLine(s); // 写入每一行命令
                    }
                }
            }

            // 启动批处理文件
            Application.OpenURL(batPath);
        }

        // 退出当前应用
        Application.Quit();
    }

    #region 本地化
    //切换语言文字
    public void OnSetLanguageButtonClick(Language language)
    {
        if (GameManager.Localization.Language!=language)
        {
            //注册字典读取成功事件
            GameManager.Event.Subscribe(LoadDictionarySuccessEventArgs.EventId, OnLoadDictionarySuccess);
            m_SelectedLanguage = language;
            if (m_SelectedLanguage == GameManager.Localization.Language)
            {
                Close();
                return;
            }
            //设置持久化数据记录选择语言
            GameManager.Setting.SetString(Constant.Setting.Language, m_SelectedLanguage.ToString());
            GameManager.Setting.Save();
            //设置选择语言
            GameManager.Localization.Language = language;
            //清除语言字典
            GameManager.Localization.RemoveAllRawStrings();
            //加载语言字典
            LoadDictionary("Default");
        }
    }
    private void LoadDictionary(string dictionaryName)
    {
        string dictionaryAssetName = AssetUtility.GetDictionaryAsset(dictionaryName, false);
        GameManager.Localization.ReadData(dictionaryAssetName, this);
    }
    private void OnLoadDictionarySuccess(object sender, GameEventArgs e)
    {
        LoadDictionarySuccessEventArgs ne = (LoadDictionarySuccessEventArgs)e;
        if (ne.UserData != (object)this)
        {
            return;
        }
        //抛出切换字体事件
        GameManager.Event.Fire(this, LocalizationChangeEventArgs.Create(GameManager.Localization.Language));
        //注销字典读取成功事件
        GameManager.Event.Unsubscribe(LoadDictionarySuccessEventArgs.EventId, OnLoadDictionarySuccess);
    }
    #endregion
}
